/*
 * TraitEditorFrame.java
 *
 * Created on December 1, 2007, 5:01 PM
 * @author Team KARP
 */

package protovitae.ui;

import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.awt.Point;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import protovitae.data.ConcreteGene;

public class TraitEditorFrame extends javax.swing.JFrame {
    protovitae.ui.MainWindow parent; //The window that created this one

    /**
     * Creates new form TraitEditorFrame
     */
    public TraitEditorFrame(protovitae.ui.MainWindow parent) {
        this.parent = parent;
        initComponents();
        // txtEatCode.enableInputMethods(rootPaneCheckingEnabled);
        initPosition();
    }
    
    private void initPosition() {
        Point parentPoint = parent.getLocation();
        int parentX = (int)parentPoint.getX();
        int parentY = (int)parentPoint.getY();
        int parentHeight = parent.getHeight();
        int parentWidth = parent.getWidth();
        
        Point viewPoint = this.getLocation();
        int viewX = (int)viewPoint.getX();
        int viewY = (int)viewPoint.getY();
        int viewHeight = this.getHeight();
        int viewWidth = this.getWidth();
        
        int newX = parentX + ((parentWidth / 2) - (viewWidth / 2));
        int newY = parentY + ((parentHeight / 2) - (viewHeight / 2));
        
        this.setLocation(new Point(newX, ((newY < 0)? 0: newY)));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlTraitEditor = new TraitEditorPanel(parent);
        mnuBar = new javax.swing.JMenuBar();
        mnuFile = new javax.swing.JMenu();
        mnuFileImport = new javax.swing.JMenuItem();
        mnuFileExport = new javax.swing.JMenuItem();
        mnuFileSep1 = new javax.swing.JSeparator();
        mnuFileClose = new javax.swing.JMenuItem();
        mnuEdit = new javax.swing.JMenu();
        mnuEditCut = new javax.swing.JMenuItem();
        mnuEditCopy = new javax.swing.JMenuItem();
        mnuEditPaste = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Trait Editor");
        getContentPane().add(pnlTraitEditor, java.awt.BorderLayout.CENTER);

        mnuFile.setText("File");

        mnuFileImport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        mnuFileImport.setText("Import existing trait...");
        mnuFileImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuFileImportActionPerformed(evt);
            }
        });
        mnuFile.add(mnuFileImport);

        mnuFileExport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        mnuFileExport.setText("Export this trait...");
        mnuFileExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuFileExportActionPerformed(evt);
            }
        });
        mnuFile.add(mnuFileExport);
        mnuFile.add(mnuFileSep1);

        mnuFileClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
        mnuFileClose.setText("Close trait");
        mnuFileClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuFileCloseActionPerformed(evt);
            }
        });
        mnuFile.add(mnuFileClose);

        mnuBar.add(mnuFile);

        mnuEdit.setText("Edit");

        mnuEditCut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        mnuEditCut.setText("Cut");
        mnuEditCut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuEditCutActionPerformed(evt);
            }
        });
        mnuEdit.add(mnuEditCut);

        mnuEditCopy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        mnuEditCopy.setText("Copy");
        mnuEditCopy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuEditCopyActionPerformed(evt);
            }
        });
        mnuEdit.add(mnuEditCopy);

        mnuEditPaste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        mnuEditPaste.setText("Paste");
        mnuEditPaste.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuEditPasteActionPerformed(evt);
            }
        });
        mnuEdit.add(mnuEditPaste);

        mnuBar.add(mnuEdit);

        setJMenuBar(mnuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /** The user selected cut frm the edit menu. Perform the cut operation
     * @param evt The event sent when cut was selected.
     */
    private void mnuEditCutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuEditCutActionPerformed
        ((TraitEditorPanel)this.pnlTraitEditor).cut();
    }//GEN-LAST:event_mnuEditCutActionPerformed

    /** The user selected copy from the edit menu. Perform the copy action.
     * @param evt The event sent to this event handler.
     */
    private void mnuEditCopyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuEditCopyActionPerformed
        ((TraitEditorPanel)this.pnlTraitEditor).copy();
    }//GEN-LAST:event_mnuEditCopyActionPerformed

    /** The user selected paste from the edit menu. Performs the paste operation
     * @param evt The event that triggered this function to be called.s
     */
    private void mnuEditPasteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuEditPasteActionPerformed
        ((TraitEditorPanel)this.pnlTraitEditor).paste();
    }//GEN-LAST:event_mnuEditPasteActionPerformed

    /** Add the current modifier entered to the list
     * @param evt The event called whe nthe Add button was clicked
     **/
    /** Delete the selected row from the list
     * @param evt The event that triggers this event handler
     **/
    /** Edit the selected row, by removing it from the list and throwing it back down below
     * @param evt The event that triggers this event handler.
     **/
    /** Event called when close is selected from the file menu. Prompt the user to save unsaved chages, then close the window.
     * @param evt The event that triggers this handler.
     */
    private void mnuFileCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuFileCloseActionPerformed
        if(JOptionPane.showConfirmDialog(this, "Would you like to export your changes?", "Export changes?", JOptionPane.YES_NO_OPTION)  ==  JOptionPane.YES_OPTION){
            mnuFileExportActionPerformed(null);
        }
        this.dispose();
    }//GEN-LAST:event_mnuFileCloseActionPerformed

    /** User selected Import from the file menu. Call the load functions.
     * @param evt The event assocated with this action.
     */
    private void mnuFileImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuFileImportActionPerformed
        JFileChooser fbox = new JFileChooser();
        
        fbox.setFileFilter(new FileXMLFilter());
        if(fbox.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
            try{
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder loader = factory.newDocumentBuilder();
                Document loadDocument = loader.parse(fbox.getSelectedFile());
                
                NodeList docnodes = loadDocument.getChildNodes();
                if(docnodes.item(0).getNodeName().equals("protovitae_gene")){
                    this.getPanel().getEdit().load((Element)docnodes.item(0));
                }
                this.getPanel().setEdit(this.getPanel().getEdit());
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_mnuFileImportActionPerformed

private void mnuFileExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuFileExportActionPerformed
    JFileChooser fbox = new JFileChooser();
    Object gene = this.getPanel().getEdit();

    fbox.setFileFilter(new FileXMLFilter());
    if (fbox.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        try {
            //Create initial XML Document and root element
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder loader = factory.newDocumentBuilder();
            Document saveDocument = loader.newDocument();
            Element root = saveDocument.createElement("protovitae_gene");

            ((ConcreteGene) (gene)).save(root, saveDocument);
            saveDocument.appendChild(root);

            //Go save!
            XMLSerializer serializer = new XMLSerializer();
            if(!fbox.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".xml"))
                fbox.setSelectedFile(new File(fbox.getSelectedFile().getAbsolutePath().concat(".xml")));
            FileWriter fw = new FileWriter(fbox.getSelectedFile());
            serializer.setOutputCharStream(fw);
            serializer.serialize(saveDocument);

            serializer.endDocument();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}//GEN-LAST:event_mnuFileExportActionPerformed

    /** Return the panel inside of this Window **/
    public TraitEditorPanel getPanel(){
        return (TraitEditorPanel)pnlTraitEditor;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuBar mnuBar;
    private javax.swing.JMenu mnuEdit;
    private javax.swing.JMenuItem mnuEditCopy;
    private javax.swing.JMenuItem mnuEditCut;
    private javax.swing.JMenuItem mnuEditPaste;
    private javax.swing.JMenu mnuFile;
    private javax.swing.JMenuItem mnuFileClose;
    private javax.swing.JMenuItem mnuFileExport;
    private javax.swing.JMenuItem mnuFileImport;
    private javax.swing.JSeparator mnuFileSep1;
    private javax.swing.JPanel pnlTraitEditor;
    // End of variables declaration//GEN-END:variables
}
